<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-calendar"></i> 用户管理 </el-breadcrumb-item>
                <el-breadcrumb-item>用户添加</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-row>
                <el-col :span="11">
                    <div class="form-box">
                        <el-form ref="form" :model="form" label-width="80px" :rules="rules">
                            <el-form-item label="员工编号" prop="tid">
                                <el-input v-model="form.tid" style="width: 60%"></el-input>
                            </el-form-item>

                            <el-form-item label="初始密码" prop="password">
                                <el-input v-model="form.password" type="password" style="width: 60%"></el-input>
                            </el-form-item>

                            <el-form-item label="确认密码" prop="password2">
                                <el-input v-model="form.password2" type="password" style="width: 60%"></el-input>
                            </el-form-item>

                            <el-form-item label="昵称" prop="nickName">
                                <el-input v-model="form.nickName" style="width: 60%"></el-input>
                            </el-form-item>

                            <el-form-item label="状态">
                                <el-switch v-model="form.status" :active-value="'01'" :inactive-value="'00'"></el-switch>
                            </el-form-item>
                            <el-form-item label="选择角色">
                                <el-checkbox-group v-model="form.roles">
                                    <el-checkbox :label="item.id" name="role" v-for="(item, index) in roles" :key="index">{{
                                        item.name
                                    }}</el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="onSubmit('form')" icon="el-icon-plus">添加用户</el-button>
                                <el-button type="warning" @click="reset('form')" icon="el-icon-refresh-right">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-col>
                <el-col :span="11">
                    <el-upload
                        class="avatar-uploader"
                        action="http://localhost:8090/icon"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="this.form.iconUrl" :src="this.form.iconUrl" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script>
export default {
    name: 'baseform',
    inject: ['reload'],
    data() {
        // 员工验证
        var checkTid = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('员工号不能为空'));
            }
            if (!/^(XY)\d{9}$/.test(value)) {
                callback(new Error('员工号格式错误'));
            } else {
                callback();
            }
        };
        // 密码验证
        var checkPWD = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('密码不能为空'));
            }
            if (!/^[0-9a-zA-Z_]{1,}$/.test(value)) {
                callback(new Error('密码只能由大小写英文字母和数字及下划线组成'));
            } else {
                callback();
            }
        };
        //密码再次校验
        var checkPWD2 = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请再次输入密码'));
            }
            if (value != this.form.password) {
                callback(new Error('密码不匹配!请重新输入'));
            } else {
                callback();
            }
        };
        return {
            roles: [],
            form: {
                tid: '',
                userName: '',
                nickName: '',
                password: '',
                password2: '',
                iconUrl: '',
                status: '01',
                roles: []
            },

            condition: {
                status: '01'
            },
            rules: {
                tid: [{ validator: checkTid, required: true, trigger: 'blur' }],
                password: [
                    { validator: checkPWD, required: true, trigger: 'blur' },
                    { min: 6, max: 15, message: '密码长度在6-15', trigger: 'blur' }
                ],
                password2: [{ validator: checkPWD2, required: true, trigger: 'blur' }]
            }
        };
    },
    created: function () {
        this.getRoles();
    },
    methods: {
        //图片上传成功后
        handleAvatarSuccess(res, file) {
            this.form.iconUrl = res.message;
        },

        //图片上传前
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },

        //获取角色
        async getRoles() {
            var d = await this.$http.post('/roleMap', this.condition);
            if (d.code == 200) {
                this.roles = d.data;
            } else [this.$message.error(d.message)];
        },

        //添加
        onSubmit(formName) {
            this.form.userName = this.form.tid;
            if (this.form.nickName.trim() == '') {
                this.form.nickName = this.form.tid;
            }
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    var d = await this.$http.post('/user', this.form);
                    if (d.code == 200) {
                        this.$message.success(d.message);
                        this.reload();
                    } else {
                        this.$message.error(d.message);
                    }
                } else {
                    this.$message.warning('请把内容填写完整!');
                }
            });
        },

        //重置
        reset(formName) {
            this.$confirm('此操作将重置所有信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    this.$refs[formName].resetFields();
                    this.form.roles = [];
                    this.form.iconUrl = '';
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消重置'
                    });
                });
        }
    }
};
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    width: 178px;
    height: 178px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>